//
//  WeiboContentViewModel.swift
//  WeiBo test
//
//  Created by Aquarius_wing on 16/5/7.
//  Copyright © 2016年 Wing. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class WeiboContentViewModel: NSObject {
    var weiboContents:[WeiboContent]=[]{
        didSet{
            NSNotificationCenter.defaultCenter().postNotificationName("weiboContentsDidSet", object: nil)
            //这就是最新的微博ID
            since_id=weiboContents.first?.id
            //当前加载的最早的微博ID
            max_id=weiboContents.last?.id
        }
    }
    
    var since_id:NSNumber?
    var max_id:NSNumber?
    
    init(count:NSNumber) {
        super.init()
        SVProgressHUD.show()
        readContent(count)
        SVProgressHUD.dismiss()
    }
    func readContent(count:NSNumber,since_id:NSNumber=0,max_id:NSNumber=0){
        //网址
        let urlString="2/statuses/friends_timeline.json"
        //请求参数,里面的变量一定要是非可选类型
        //如果为空(为可选类型的时候才可能为空)
        if UserAccountViewModel().token == nil{
            return
        }
        let parameters = ["access_token":UserAccountViewModel().token!,"count":count,"since_id":since_id,"max_id":max_id]
        NetWorkTools.sharedTools.requestJsonDict(HTTPMethod.GET, urlString: urlString, parameters: parameters) { (result, error) in
            if error != nil {
                //如果错误存在
                print("readContent error!",error)
            }
            
            //得到数据
            var weiboContents:[WeiboContent]=[]
            let statusDicts = result!["statuses"] as! [[String : AnyObject]]
            for statusDict in statusDicts{
                weiboContents.append(WeiboContent(dict: statusDict))
            }
            //最后的赋值
            if since_id == 0 && max_id == 0{
                //如果都为零,则为初始化
                self.weiboContents=weiboContents
            }else{
                if since_id != 0{
                    //获取的是最新的微博
                    self.weiboContents=weiboContents+self.weiboContents
                    return
                }
                if max_id != 0{
                    //获取的是之前的微博
                    self.weiboContents=self.weiboContents[0..<self.weiboContents.count-1]+weiboContents
                    return
                }
            }
        }
    }
}
